package com.third.clock.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.orhanobut.logger.Logger;
import com.third.clock.IRemote;
import com.third.clock.manager.ClockManager;

/**
 * Created by Administrator on 2018/7/21 0021.
 */

public class ClockService extends Service{

    private ClockManager mClockManager;

    private ServiceConnection mServiceConnection;

    private MyRemoteService myService;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return myService;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mClockManager=ClockManager.getInstace(ClockService.this);
        mClockManager.onCreate();
        mClockManager.login(null);

        bindRemote();

        Logger.d("ClockService   onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.d("ClockService   onDestroy");
        mClockManager.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Intent intents = new Intent();
        intents.setClass(this, RemoteService.class);
        bindService(intents, mServiceConnection, Context.BIND_IMPORTANT);

        mClockManager.getLocationManager().enableBackgroundLocation();
        return START_STICKY;
    }

    private void bindRemote(){
        if (mServiceConnection == null) {
            mServiceConnection = new MyServiceConnection();
        }
        myService = new MyRemoteService();
    }

    class MyRemoteService extends IRemote.Stub {

        @Override
        public void bind() throws RemoteException {

        }
    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            ClockService.this.startService(new Intent(ClockService.this,
                    RemoteService.class));
            ClockService.this.bindService(new Intent(ClockService.this,
                    RemoteService.class), mServiceConnection, Context.BIND_IMPORTANT);

        }

    }

}
